<template>
  <div class="add_oder">
    <div class="add_oder-top">
      <div class="add_oder-top-header">
        <div class="title">
          <p>发起合同</p>
        </div>
        <div class="btn">
          <span @click="handelClickCreatOder">生成合同订单</span>
          <span>|</span>
          <span @click="handelClickBack">返回</span>
        </div>
      </div>
      <div class="add_oder-top-content">
        <div class="step">
          <stepView :active="data.stepActive" :list="data.stepList"></stepView>
        </div>
        <div class="form">
          <div class="form_top">
            <el-form ref="ruleFormRef" :rules="rules" label-position="top" style="width: 100%">
              <el-form-item label="" style="width: 100%" prop="">
                <div class="user-title">
                  <p>*<span>选择关联客户</span></p>
                </div>
                <div class="serch">
                  <el-input
                    v-model="data.userMessage"
                    placeholder="搜索客户姓名、手机号进行关地址"
                    class="input-with-select"
                    @input="handelChangeSerch"
                  >
                    <template #append>
                      <el-button :icon="Search" @click="handelChangeSerch" />
                    </template>
                  </el-input>
                  <div class="user_addss" v-if="data.isShowUserList">
                    <div class="list">
                      <ul>
                        <li
                          v-for="(item, index) in data.userList"
                          :key="index"
                          @click="handelClickUserListItem(item, index)"
                          :class="data.num === index ? 'active' : ''"
                        >
                          <div>
                            <p>{{ item.receivingName }}</p>
                            <p><span>电话:</span>{{ item.receivingMobile }}</p>
                            <p><span>地址:</span>{{ item.address }}</p>
                          </div>
                          <div>
                            <el-icon v-show="data.num === index" :color="data.num === index ? '#007DFF' : ''"
                              ><SuccessFilled
                            /></el-icon>
                          </div>
                        </li>
                      </ul>
                    </div>
                    <div class="btn">
                      <el-button @click="handelClickCacl">取消</el-button>
                      <el-button type="primary" @click="handelClickSubmit">确定关联</el-button>
                    </div>
                  </div>
                </div>
                <!-- <div class="btn">
                  <el-button type="primary">新增客户</el-button>
                </div> -->
              </el-form-item>
              <el-form-item label="客户信息">
                <div class="customer_message_list">
                  <div class="custom_message" v-if="Object.keys(data.chooseCustom).length > 0">
                    <p>姓名:{{ data.chooseCustom.receivingName }}</p>
                    <p>电话:{{ data.chooseCustom.receivingMobile }}</p>
                    <p>项目地址:{{ data.chooseCustom.address }}</p>
                  </div>
                  <p v-else>暂无关联客户信息,请选择客户</p>
                </div>
              </el-form-item>
              <!-- <el-form-item label="关联业务员信息">
                <div class="customer_message_list">
                    <p>暂未关联业务信息,请选择关联</p>
                </div>
              </el-form-item> -->
              <el-form-item label="">
                <div class="address">
                  <div>收货信息</div>
                  <div v-if="Object.keys(data.getAddress).length > 0">
                    <!-- <span @click="handelClickChangeAderss(data.getAddress)">修改地址</span> -->
                    <!-- <span></span> -->
                    <span @click="handelClickAderssManage(data.getAddress)">地址管理</span>
                  </div>
                </div>
                <div class="customer_message_list">
                  <div class="custom_message" v-if="Object.keys(data.getAddress).length > 0">
                    <p>姓名:{{ data.getAddress.receivingName }}</p>
                    <p>电话:{{ data.getAddress.receivingMobile }}</p>
                    <p>项目地址:{{ data.getAddress.receivingAreaDetail }}{{ data.getAddress.receivingAddress }}</p>
                  </div>
                  <p v-else>暂无关联客户收货地址</p>
                </div>
              </el-form-item>
              <el-form-item>
                <div class="order_status">
                  <span class="title">订单状态</span>
                  <el-radio-group v-model="data.orderStatus" class="ml-4">
                    <el-radio value="1" size="large">意向订单</el-radio>
                    <el-radio value="2" size="large">首次订单</el-radio>
                    <el-radio value="3" size="large">最终订单</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <div class="add_oder-botton">
      <div class="header">
        <div class="title">商品信息</div>
        <div class="btn">
          <el-button type="primary" @click="handelBatchDelet">批量删除</el-button>
          <el-button type="primary" @click="handelImportExcel">导入SKU编码ID</el-button>
          <el-button @click="handelDownloadSku">下载SKU编码ID模板</el-button>
        </div>
      </div>
      <div class="product_information">
        <el-table
          :data="data.importExcelList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-if="data.importExcelList.length > 0"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品信息" width="320">
            <template #default="scope">
              <div class="sp_content">
                <div>
                  <img class="image" :src="scope.row.mainPicUrl || defaultImage" alt="" />
                </div>
                <div>
                  <p>{{ scope.row.productAliasName }}</p>
                  <p>{{ scope.row.skuSpecification }}</p>
                  <p>sku编码:{{ scope.row.skuCode }}</p>
                  <p>ID:{{ scope.row.productId }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" prop="unitPrice"></el-table-column>
          <el-table-column label="数量" width="260">
            <template #default="scope">
              <!-- <el-input
                type="number"
                v-model="scope.row.commodityNum"
                :min="1"
                @input="handelChangeCommodityNum(scope.row.salePrice, scope.row)"
                style="width: 100px"
              ></el-input> -->
              <el-input-number
                :max="9999"
                :precision="0"
                controls-position="right"
                style="width: 160px"
                v-model="scope.row.commodityNum"
                @change="
                  () => {
                    handelChangeCommodityNum(scope.row.salePrice, scope.row);
                  }
                "
              ></el-input-number>
              <span style="margin-left: 10px">{{ useCodeArrStore().getDictName("shop_unit", scope.row.productUnit) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品清单数量" prop="detailNum"></el-table-column>
          <el-table-column label="涨价/减价(减价为负)" width="260">
            <template #default="scope">
              <!-- <el-input
                v-model="scope.row.salePrice"
                :placeholder="scope.row.salePrice"
                type="number"

                @input="handelInputSalePrice(scope.row.salePrice, scope.row)"
                class="input-with-select"
              >
                <template #prepend>
                  <span>{{ isIncrease(scope.row.salePrice) }}</span>
                </template>
              </el-input> -->

              <span>{{ isIncrease(scope.row.salePrice) }}</span>
              <el-input-number
                :max="100000"
                :precision="2"
                controls-position="right"
                style="width: 160px"
                v-model="scope.row.salePrice"
                @change="
                  () => {
                    handelInputSalePrice(scope.row.salePrice, scope.row);
                  }
                "
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="实付价格" prop="actualPrice"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" link size="small" @click="handelClickDelet(scope.row)">删除商品</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无商品信息, 您可以添加商品到当前订单合同中" />
      </div>
      <!-- 计算涨价降价总和价格 -->
      <div class="total_price">
        <div class="total_price-left">
          <div>
            <span>优惠金额:</span>
            <!-- <el-input-number
              v-model="data.preferentialMoney"
              :controls="false"
              :min="0"
              type="number"
              style="width: 100px"
              @input="handelInputPreferentialMoney"
            /> -->
            <el-input v-model="data.preferentialMoney" placeholder="" @input="handelInputPreferentialMoney"></el-input>
          </div>
          <div>
            <span>其他费用:</span>
            <!-- <el-input-number
              v-model="data.otherMoney"
              :controls="false"
              :min="0"
              style="width: 100px"
              @change="handelInputOther"
            /> -->
            <el-input v-model="data.otherMoney" placeholder="" @input="handelInputOther"></el-input>
          </div>
        </div>
        <div class="total_price-right">
          订单总金额:<span>￥{{ data.payTotal }}</span>
        </div>
      </div>
      <!-- 备注 -->
      <div class="remarks">
        <span>订单备注</span>
        <!-- <el-input v-model="data.remarks" type="textarea" maxlength="200" show-word-limit /> -->
        <RemarkEditor v-model="data.remarks" />
      </div>
    </div>
    <!-- 导入sku表格上传 -->
    <el-dialog v-model="data.isShowUpdate">
      <!--test prod -->
      <el-upload
        class="upload-demo"
        :action="globalConfig.contractOrderUpload"
        :headers="{
          Authorization: `Bearer ${getLocalCache(globalConfig.tokenAttr)}`
        }"
        name="file"
        drag
        multiple
        :on-success="handelUpdateFile"
        :show-file-list="false"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      </el-upload>
    </el-dialog>
    <!-- 生成订单提示弹框 -->
    <dialog-View :isShow="data.errOderDialog" :width="'30%'">
      <div class="top">
        <el-icon size="50" color="red">
          <Warning />
        </el-icon>
      </div>
      <div class="center">
        <p>请添加并关联客户信息，业务员，商品信息，后再生成订单合同</p>
      </div>
      <div class="botton">
        <el-button @click="data.errOderDialog = false">取消</el-button>
        <el-button type="primary" @click="data.errOderDialog = false"> 我知道了 </el-button>
      </div>
    </dialog-View>
    <!-- 修改收货地址 -->
    <dialog-View :isShow="data.isShowAdess" :title="'修改地址'" :width="'30%'">
      <form-View
        :formList="data.cAddressList"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        @update="handelUpdateAdress"
        @back="data.isShowAdess = false"
      ></form-View>
    </dialog-View>
    <!-- 地址管理 -->
    <dialog-View :isShow="data.isShowAdessManage" :title="'地址管理'" :width="'50%'" @close="handelClose">
      <adess-Manage
        :list="data.customerAddressList"
        :activeItem="receiveObj"
        @delete="handelClickRemoveAdess"
        @back="handelClickBackAdessManage"
        @addAdess="handelClickAddAdess"
        @setDefault="handeSetDefault"
        @save="handelClickSave"
        @edit="handelClickEdit"
      ></adess-Manage>
    </dialog-View>
    <!-- 新增收货地址 -->
    <dialog-View :isShow="data.isShowNewAdess" :title="'新增地址'" :width="'30%'">
      <form-View
        :formList="data.cAddressList"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        @update="handelUpdateNewAdress"
        @back="data.isShowNewAdess = false"
      ></form-View>
    </dialog-View>
    <!-- 编辑收货地址 -->
    <dialog-View :isShow="data.isShowEditAdess" :title="'编辑地址'" :width="'30%'">
      <form-View
        :formList="data.cAddressLists"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        :editItem="data.editItem"
        @update="handelUpdateEditAdress"
        @back="data.isShowEditAdess = false"
      ></form-View>
    </dialog-View>
    <!-- 导入文件错误提示=框 -->
    <dialog-View :isShow="data.importError" :width="'50%'">
      <div class="top">
        <el-icon size="50" color="#2BA471" v-if="data.isImportSucess">
          <CircleCheck />
        </el-icon>
        <el-icon v-else size="50" color="#D54941"><CircleClose /></el-icon>
      </div>
      <div class="err-content" v-if="!data.isImportSucess">
        <div>
          <p>出错了</p>
          <p>失败原因。您导入的数据模板中，存在必填项数据缺失，根据提示内容，请补充完整后重新导入</p>
          <div>
            <p>{{ data.errMessage }}</p>
          </div>
        </div>
      </div>
      <div v-else class="sucess-content">
        <div>
          <p>导入商品成功</p>
          <p>
            导入商品{{
              data.importExcelList.length
            }}条，商品导入后存放在预发布商品列表，需要进行补充商品部份信息后，提交商品上架。
          </p>
          <div>
            <p>完善内容与检查事项：</p>
            <p>请在合同中完善商品合同价格，数量，以及优惠信息等，确认无误后，提交生成合同对应合同状态。</p>
          </div>
        </div>
      </div>
      <div class="botton">
        <el-button type="primary" @click="data.importError = false"> 我知道了 </el-button>
      </div>
    </dialog-View>
  </div>
</template>
<script setup>
// 资源导入
import { reactive, ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { getLocalCache } from "@/utils/cache";
import globalConfig from "@/settings";
import { Search, SuccessFilled, UploadFilled, Warning, CircleCheck, CircleClose } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import china from "@/utils/china.json";
import useCodeArrStore from "@/store/modules/select";
// 导入api
import {
  customAddress,
  relationCustomerAddress,
  createOrder,
  templateDownload,
  getCustomerAddressList,
  deleteCustomerAddress,
  saveCustomerAddress
} from "@/apis/order/index";
// import config from "@/settings";
// 组件导入
import stepView from "../components/step.vue";
import dialogView from "../components/dialogView.vue";
import formView from "../components/formView.vue";
import adessManage from "./components/adessManage.vue";
import RemarkEditor from "@/components/RemarkEditor";
// 变量声明
const useRout = useRouter();
const chinas = ref(china);
const data = reactive({
  stepList: [
    { title: "编辑合同订单", description: "" },
    { title: "关联客户信息", description: "" },
    { title: "添加合同商品", description: "" }
    // { title: "关联业务信息", description: "" }
  ],
  userList: [],
  orderStatus: "1",
  remarks: "",
  userMessage: "",
  num: -1,
  isShowUserList: false,
  chooseCustom: {}, //搜索后选择的客户对象真正渲染的对象
  chooseCustomCopy: {}, //搜索后选择的客户对象
  getAddress: {}, //收货地址对象
  stepActive: 1, //步骤进度
  isShowUpdate: false, //导入弹框
  importExcelList: [], //导入成功后的数据
  errOderDialog: false, //错误提示弹框
  payTotal: 0, //最后的总金额
  payTotalCope: 0,
  preferentialMoney: 0, //优惠金额
  otherMoney: 0, //其他费用
  // 修改收货地址-----
  isShowAdess: false,
  cAddressList: [
    { label: "收货人", model: "receivingName", type: "input", max: 10 },
    { label: "手机", model: "receivingMobile", type: "input", max: 11 },
    { label: "收货地址", model: "receivingAddress", type: "cascader", options: chinas, max: 50 },
    { label: "详细地址", model: "receivingAreaDetail", type: "input", max: 50 }
  ],
  cAddressLists: [
    { label: "收货人", model: "receivingName", type: "input", max: 10 },
    { label: "手机", model: "receivingMobile", type: "input", max: 11 },
    { label: "收货地址", model: "receivingAreaIds", type: "cascader", options: chinas, max: 50 },
    { label: "详细地址", model: "receivingAddress", type: "input", max: 50 }
  ],
  rulesOrderAdess: {
    receivingName: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 1, max: 200, message: "请输入名称", trigger: "blur" }
    ],
    receivingMobile: [
      { required: true, message: "请输入电话", trigger: "blur" },
      { min: 1, max: 200, message: "请输入电话", trigger: "blur" }
    ],
    receivingAddress: [
      {
        required: true,
        message: "请选择地址",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            return callback(new Error("请选择一个地址"));
          }
          return callback();
        }
      }
    ],
    receivingAreaDetail: [
      { required: true, message: "请输入详细地址", trigger: "blur" },
      { min: 1, max: 300, message: "请输入详细地址", trigger: "blur" }
    ]
  },
  // 修改收货地址----end

  // 地址管理--------------

  isShowAdessManage: false,
  customerAddressList: [], //客户收货地址列表
  customerId: "",
  isShowNewAdess: false,
  defaultItem: {}, //选择默认后地址的一条数据对象
  isShowEditAdess: false,
  editItem: {}, //编辑地址的对象
  // 地址管理-------------end
  // 导入文件-------------
  importError: false,
  isImportSucess: true,
  // 导入文件------------end
  errMessage: "",
  copyExcileList: [] //原始数据
});
const ruleFormRef = ref();
const rules = ref({
  userMessage: [{ required: true, message: "", trigger: "blur" }]
});
const picValue = ref(0); // 原来的初始价格
const handelInputSalePrice = (v, item) => {
  data.copyExcileList.map(it => {
    if (it.businessSkuId === item.businessSkuId) {
      picValue.value = it.actualPrice;
    }
  });
  item.actualPrice = (Number(item.unitPrice) + Number(v)) * Number(item.commodityNum);
};
// 监听导入的数据数据获取总价
watch(
  () => data.importExcelList,
  list => {
    const res = publicTotal(list);
    data.payTotal = (Number(res) + Number(data.otherMoney) - Number(data.preferentialMoney)).toFixed(2);
  },
  { deep: true, immediate: true }
);
// 监听优惠金额
watch(
  () => data.preferentialMoney,
  v => {
    const res = publicTotal(data.importExcelList);
    data.payTotal = (Number(res) + Number(data.otherMoney) - Number(v)).toFixed(2);
  },
  { deep: true }
);
// 监听其他费用
watch(
  () => data.otherMoney,
  v => {
    const res = publicTotal(data.importExcelList);
    data.payTotal = (Number(res) - Number(data.preferentialMoney) + Number(v)).toFixed(2);
  },
  { deep: true }
);
const picValues = ref(0);
// 计算实际价格
const handelChangeCommodityNum = (v, item) => {
  if (item.commodityNum < 1) {
    item.commodityNum = 1;
    return;
  }
  item.actualPrice = Number(item.commodityNum) * (Number(item.unitPrice) + Number(v));
  item.detailNum = Number(item.commodityNum) * Number(item.partNum);
  // data.copyExcileList.map(it => {
  //   if (it.businessSkuId === item.businessSkuId) {
  //     picValue.value = it.actualPrice;
  //   }
  // });

  // item.actualPrice = (Number(picValues.value) + Number(v) * Number(item.commodityNum)).toFixed(2);
};
// 计算总计公共方法结果
function publicTotal(list) {
  const sum = list.reduce((accumulator, currentObject) => {
    return accumulator + (Number(currentObject.unitPrice) + Number(currentObject.salePrice)) * currentObject.commodityNum;
  }, 0);
  return sum;
}
// 如果输入不为数字时候其他金额
const handelInputOther = () => {
  // if (typeof value === "object") {
  //   data.otherMoney = 0;
  // }
  data.otherMoney = data.otherMoney.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};
// 如果输入不为数字时候优惠金额
const handelInputPreferentialMoney = () => {
  // console.log(typeof value, "这是个撒子");
  // if (value == "null") {
  //   data.preferentialMoney = 0;
  //   console.log(data.preferentialMoney,'data.preferentialMoney');
  //   console.log("----");
  // }
  // if (typeof value === "object") {
  //   data.preferentialMoney = 0;
  // }
  data.preferentialMoney = data.preferentialMoney.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
};

const handelClickBack = () => {
  useRout.push({
    path: "/oder"
  });
};
const handelClickUserListItem = (item, index) => {
  data.num = index;
  console.log(index, data.num);
  data.chooseCustomCopy = item;
};
const handelChangeSerch = () => {
  data.isShowUserList = true;
  customAddress(data.userMessage)
    .then(res => {
      console.log(res);
      if (res.code === 200) {
        data.userList = res.data;
      }
    })
    .catch(err => {
      console.log(err);
    });
};
const handelClickCacl = () => {
  data.isShowUserList = false;
  data.userMessage = "";
};
// 关闭弹框
const handelClose = () => {
  data.isShowAdessManage = false;
};
// 判断是否涨价
const isIncrease = n => {
  if (n < 0) {
    return "降价";
  } else {
    return "涨价";
  }
};
const handelClickSubmit = () => {
  data.isShowUserList = false;
  data.userMessage = "";
  // 确定后的客户对象
  data.chooseCustom = data.chooseCustomCopy;
  console.log(data.chooseCustom, "客户...");
  relationCustomerAddress(data.chooseCustom)
    .then(res => {
      console.log(res, "sssss");
      if (res.code === 200) {
        data.stepActive = 2;
        data.getAddress = res.data;
        console.log(data.getAddress, "客户地址...");
      }
    })
    .catch(err => {
      console.log(err);
    });
};
// 导入sku编码id
const handelImportExcel = () => {
  data.isShowUpdate = true;
};
const handelUpdateFile = res => {
  if (res.code === 200) {
    data.isShowUpdate = false;
    data.stepActive = 3;
    data.importExcelList = res.data;
    // 保留一份原始数据
    let copy = JSON.stringify(res.data);
    let copyData = JSON.parse(copy);
    data.copyExcileList = copyData;
    data.isImportSucess = true;
    data.importError = true;
  } else {
    console.log(222);
    data.errMessage = res.msg;
    data.importError = true;
    data.isShowUpdate = false;
    data.isImportSucess = false;
  }
};
// 下载sku
const handelDownloadSku = () => {
  templateDownload({}).then(res => {
    const blob = new Blob([res]);
    const url = window.URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    // 设置文件名
    link.setAttribute("download", "SKU编码模板.xlsx"); // 'filename.ext' 替换为实际文件名

    // 触发点击事件
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  });
};
const handelClickCreatOder = () => {
  // 判断是否填写相应信息
  const { chooseCustom, getAddress, importExcelList } = data;
  if (Object.keys(chooseCustom).length === 0 || Object.keys(getAddress).length === 0 || importExcelList.length === 0) {
    data.errOderDialog = true;
    return;
  } else {
    const { customerId, receivingName, receivingMobile, receivingAddress, receivingAreaDetail, receivingAreaIds, customerName } =
      data.getAddress;
    const date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    // 使用padStart方法确保至少有两个字符，不足则用0填充
    hours = hours.toString().padStart(2, "0");
    minutes = minutes.toString().padStart(2, "0");
    seconds = seconds.toString().padStart(2, "0");
    let nowDate = y + "-" + m + "-" + d + " " + hours + ":" + minutes + ":" + seconds;
    let obj = {
      salePrice: data.preferentialMoney, //优惠金额
      otherPrice: data.otherMoney, //其他费用
      actualPrice: data.payTotal, //实收金额;订单总金额-优惠费用+其他费用
      customerId: customerId, //客户信息-客户id;来自crm客户信息表crm_customer_info主键
      customerName: chooseCustom.receivingName, //客户信息-客户姓名;冗余
      customerMobileCode: receivingMobile, //客户信息-客户姓名;冗余
      customerAddress: receivingAreaDetail + receivingAddress,
      receivingName: receivingName, //客户信息-项目地址;冗余
      receivingMobile: receivingMobile, //收货信息-电话
      receivingAreaIds: receivingAreaIds, //收货信息区域id，多个用,隔开；如500000,500100,500105，代表重庆市市辖区江北区
      receivingAreaDetail: receivingAreaDetail, //收货信息 区域描述 如重庆市市辖区江北区
      receivingAddress: receivingAddress, //收货信息-地址 如观音桥街道xxx大厦10栋10-1
      remark: data.remarks, //备注
      orderTime: nowDate, //订单时间，补录的时候需要，如果不填，默认服务器时间
      skuList: data.importExcelList,
      orderStatus: Number(data.orderStatus)
    };
    createOrder(obj)
      .then(res => {
        console.log(res, "订单");
        if (res.code === 200) {
          ElMessage({
            message: "生成订单成功",
            type: "success"
          });
          setTimeout(() => {
            handelClickBack();
          }, 2000);
        }
      })
      .catch(err => {
        console.log(err);
      });
  }
};
// 修改收货地址---------
// const handelClickChangeAderss = item => {
//   data.isShowAdess = true;
//   console.log(item, "收货地址");
// };
const handelUpdateAdress = item => {
  console.log(data.getAddress, "data.getAddress", item);

  data.getAddress.receivingAreaDetail = item.receivingAreaDetail;
  data.getAddress.receivingAreaIds = item.receivingAddress.join(",");
  data.getAddress.receivingMobile = item.receivingMobile;
  data.getAddress.receivingName = item.receivingName;
  data.isShowAdess = false;
  // console.log(item, "xiuga", data.chooseCustom, "-----", data.getAddress);
};
//删除商品
const handelClickDelet = item => {
  ElMessageBox.confirm("确定删除?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    let idToRemove = item.businessSkuId;
    data.importExcelList = data.importExcelList.filter(item => item.businessSkuId !== idToRemove);
    ElMessage({
      message: "删除成功",
      type: "success"
    });
  });
};
// 批量删除
const choseArr = ref([]);
const handelBatchDelet = () => {
  if (choseArr.value.length <= 0) {
    ElMessage({
      message: "请选择要删除的商品",
      type: "warning"
    });
    return;
  }
  ElMessageBox.confirm("确定删除选择的商品?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    let array1 = data.importExcelList.filter(obj1 => !choseArr.value.some(obj2 => obj2.skuCode === obj1.skuCode));
    data.importExcelList = array1;
    ElMessage({
      message: "删除成功",
      type: "success"
    });
  });
};
// 选中的表格数据
const handleSelectionChange = item => {
  choseArr.value = item;
};
// 修改收货地址--------edn

// 地址管理---------------
const receiveObj = ref({}); //存储暂时的点击地址管理收货信息
const handelClickAderssManage = item => {
  console.log(item);
  receiveObj.value = item;
  data.customerId = item.customerId;
  data.isShowAdessManage = true;
  getCustomerAddressLists(item.customerId);
};
const getCustomerAddressLists = id => {
  getCustomerAddressList(id).then(res => {
    if (res.code === 200) {
      res.data.map(it => {
        if (it.defaultFlag === 1) {
          it.isDefault = true;
        } else {
          it.isDefault = false;
        }
      });
      data.customerAddressList = res.data;
    }
  });
};
const handelClickRemoveAdess = item => {
  ElMessageBox.confirm("确定删除?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteCustomerAddress({ receivingAddressId: item.receivingAddressId }).then(() => {
      ElMessage({
        message: "删除地址成功",
        type: "success"
      });
      getCustomerAddressLists(data.customerId);
    });
  });
};
const handelClickBackAdessManage = () => {
  data.isShowAdessManage = false;
};
const handelUpdateNewAdress = (item, detailAdess) => {
  let obj = {
    customerId: data.customerId,
    receivingAreaIds: item.receivingAddress.join(","),
    receivingName: item.receivingName,
    receivingMobile: item.receivingMobile,
    receivingAreaDetail: detailAdess,
    receivingAddress: item.receivingAreaDetail
  };
  // return
  saveCustomerAddress(obj)
    .then(res => {
      console.log(res, "新增收货地址");
      ElMessage({
        message: "新增地址成功",
        type: "success"
      });
      data.isShowNewAdess = false;
      getCustomerAddressLists(data.customerId);
    })
    .catch(err => {
      console.log(err);
    });
};
const handelClickAddAdess = () => {
  data.isShowNewAdess = true;
};
// 设置默认地址
const handeSetDefault = (item, index) => {
  console.log(item, "选中为默认值的项---------");

  data.defaultItem = item;
  data.customerAddressList.map((it, i) => {
    if (index === i) {
      it.isDefault = true;
    } else {
      it.isDefault = false;
    }
  });
  // return
  let obj = {
    ...item
  };
  obj.defaultFlag = 1;
  delete obj.isDefault;
  // 覆盖之前获取的用户信息
  data.getAddress = obj;
  saveCustomerAddress(obj)
    .then(() => {
      ElMessage({
        message: "设置默认地址成功",
        type: "success"
      });
    })
    .catch(err => {
      console.log(err);
    });
};
const handelClickSave = item => {
  data.getAddress = item;
  data.isShowAdessManage = false;
};
// 编辑获取新值的对象
const handelUpdateEditAdress = (item, adrss) => {
  // console.log(item,'ppp');
  // return
  let obj = {
    receivingAddressId: data.editItem.receivingAddressId,
    receivingName: item.receivingName,
    receivingMobile: item.receivingMobile,
    receivingAddress: item.receivingAddress,
    receivingAreaDetail: adrss,
    receivingAreaIds: item.receivingAreaIds.join(",")
  };
  saveCustomerAddress(obj)
    .then(res => {
      console.log(res, "保存");
      ElMessage({
        message: "编辑地址成功",
        type: "success"
      });
      getCustomerAddressLists(data.customerId);
      data.isShowEditAdess = false;
    })
    .catch(err => {
      console.log(err);
    });
};
// 点击编辑事件
const handelClickEdit = item => {
  console.log(item, "编辑的对象");
  let obj = JSON.stringify(item);
  let objCopy = JSON.parse(obj);
  objCopy.receivingAreaIds = objCopy.receivingAreaIds.split(",");
  // 保存编辑的对象
  // return
  data.editItem = objCopy;
  data.isShowEditAdess = true;
};
// 地址管理-------------end
onMounted(() => {
  chinas.value.map(item => {
    // 第一层
    item.label = item.name;
    item.value = item.cityCode;
    if (item.hasOwnProperty("children")) {
      console.log("第二层");
      // 第二层
      item.children.map(citem => {
        citem.label = citem.name;
        citem.value = citem.cityCode;
        if (citem.hasOwnProperty("children")) {
          // 第三层
          citem.children.map(ccitem => {
            ccitem.label = ccitem.name;
            ccitem.value = ccitem.cityCode;
          });
        }
      });
    }
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
